package com.yinyong;

/**
 * Time    : 2023/3/18 20:04
 * Author  : 王摇摆
 * FileName: RefTrans.java
 * Software: IntelliJ IDEA 2020.2.2
 * Blog    ：https://blog.csdn.net/weixin_44943389?type=blog
 */

import javafx.scene.input.TouchEvent;

/**
 * 本实例实现引用传递交换两个值
 * 使用类对象引用
 */
public class RefTrans {
    public static void main(String[] args) {
        Student s1 = new Student("张三", 23);
        Student s2 = new Student("李四", 24);

//        swap(s1, s2);//成功交换，Java中的是值传递，传递的是对象引用的副本，但是程序要写好这个东西
        swap1(s1,s2);//交换失败，记住，Java中只有值传递，传递的是对象引用的副本，所以形参的改变并不会影响实参

        System.out.println("The result of main function is :");
        System.out.println(s1.toString());
        System.out.println(s2.toString());


    }

    private static void swap(Student a, Student b) {
        Student temp = new Student();
        temp.age = a.age;
        temp.name = a.name;

        a.name = b.name;
        a.age = b.age;
        b.name = temp.name;
        b.age = temp.age;

        System.out.println("The result of swap function is :");
        System.out.println(a.toString());
        System.out.println(b.toString());

    }

    private static void swap1(Student a, Student b) {
        Student temp = new Student();

        temp = a;
        a = b;
        b = temp;

        System.out.println("The result of swap1 function is :");
        System.out.println(a.toString());
        System.out.println(b.toString());


    }

}

class Student {
    String name;
    int age;


    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student() {

    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}